package com.jacky.iot.tasks;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jacky.iot.commons.InstantTypeAdapter;
import com.jacky.iot.dtos.DataFetchWrapper;
import com.jacky.iot.dtos.TimeCmd;
import com.jacky.iot.models.CpuUsage;
import com.jacky.iot.service.CpuUsageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.time.Instant;
import java.util.List;
import java.util.TimerTask;

public class WebSocketScheduleTask extends TimerTask {

    private final Logger LOG = LoggerFactory.getLogger(WebSocketScheduleTask.class);

    private final WebSocketSession session;
    private final CpuUsageService usageService;
    private final DataFetchWrapper wrapper;
    private final TimeCmd rangeTC;
    private final Gson gson = new GsonBuilder()
            .registerTypeAdapter(Instant.class, new InstantTypeAdapter())
            .create();

    public WebSocketScheduleTask(WebSocketSession session, CpuUsageService usageService,
                                 DataFetchWrapper dfw, TimeCmd windowTC) {
        this.session = session;
        this.usageService = usageService;
        this.wrapper = dfw;
        this.rangeTC = windowTC;
    }

    @Override
    public void run() {
        try {
            if (session.isOpen()) {
                List<CpuUsage> usages = usageService.fetchLastData(wrapper, rangeTC);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("fetch data:{}", usages);
                }
                String usageStr = gson.toJson(usages);
                TextMessage tm = new TextMessage(usageStr.getBytes());
                session.sendMessage(tm);
            }
        } catch (Exception e) {
            LOG.error("发送webSocket消息异常:", e);
        }
    }
}
